package com.futureway.test.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
import org.springframework.stereotype.Service;

import com.futureway.test.dao.UserRespository;
import com.futureway.test.entity.QCourse;
import com.futureway.test.entity.QUser;
import com.futureway.test.entity.QUserCourse;
import com.futureway.test.entity.User;
import com.futureway.test.service.UserService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPQLQuery;

@Service
public class UserServiceImpl extends QuerydslRepositorySupport implements UserService {

	public UserServiceImpl() {
		super(User.class);
	}

	@Autowired
	private UserRespository userRespository;

	@Override
	public Integer save(String userName) {
		User user = new User();
		user.setUserName(userName);
		user = userRespository.saveAndFlush(user);
		return user.getId();
	}

	@Override
	public List<User> findAll() {
		JPQLQuery<User> query = from(QUser.user).distinct().select(QUser.user).innerJoin(QUserCourse.userCourse)
				.on(QUser.user.id.intValue().eq(QUserCourse.userCourse.key.userId.intValue())).innerJoin(QCourse.course)
				.on(QCourse.course.id.intValue().eq(QUserCourse.userCourse.key.courseId.intValue()));
		return query.fetch();
		// return userRespository.findAll();
	}

	@Override
	public User get(Integer id) {
		return userRespository.getOne(id);
	}

	@Override
	public List<User> findAll(String userName) {
		return (List<User>) userRespository.findAll(QUser.user.userName.likeIgnoreCase("%" + userName + "%"));
	}

	@Override
	public Page<User> page(Predicate predicate, Pageable pageable) {
		return userRespository.findAll(predicate, pageable);
	}

	@Override
	public QueryResults<Tuple> page(List<Predicate> predicates, Pageable pageable) {
		JPQLQuery<Tuple> query = getQuerydsl().applyPagination(pageable,
				from(QUser.user).select(QUser.user, QCourse.course).leftJoin(QUserCourse.userCourse)
						.on(QUser.user.id.intValue().eq(QUserCourse.userCourse.key.userId.intValue()))
						.leftJoin(QCourse.course)
						.on(QCourse.course.id.intValue().eq(QUserCourse.userCourse.key.courseId.intValue())));
		return query.where(predicates.toArray(new Predicate[] {})).fetchResults();
	}

}
